package com.example.myapplication.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClient {
    private static TcpClient instance;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;

    private TcpClient() {
        try {
            socket = new Socket("192.168.1.124.", 8234);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
        } catch (Exception e) {
            e.printStackTrace();
            // 确保在初始化失败时，对象不会被使用
            out = null;
            in = null;
        }
    }

    public static synchronized TcpClient getInstance() {
        if (instance == null) {
            instance = new TcpClient();
        }
        return instance;
    }

    public void sendMessage(String message) {
        if (out != null) {
            out.println(message);
        }
    }

    public String receiveMessage() {
        try {
            if (in != null) {
                return in.readLine();
            }else {
                System.err.println("BufferedReader is null. Cannot receive message.");
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}